<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  timeRange: {
    type: String,
    default: 'day'
  }
});

const chartRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

// 生成日期标签
const generateDateLabels = computed(() => {
  const today = new Date();
  const labels = [];
  
  if (props.timeRange === 'day') {
    // 显示过去16天的数据
    for (let i = 15; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(date.getDate() - i);
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      labels.push(`${month}/${day}`);
    }
  } else if (props.timeRange === 'week') {
    // 显示过去16周的数据
    for (let i = 15; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(date.getDate() - i * 7);
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      labels.push(`${month}/${day}`);
    }
  } else if (props.timeRange === 'month') {
    // 显示过去12个月的数据
    for (let i = 11; i >= 0; i--) {
      const date = new Date(today);
      date.setMonth(date.getMonth() - i);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      labels.push(`${year}/${month}`);
    }
  }
  
  return labels;
});

// 生成随机数据
const generateRandomData = (min: number, max: number, count: number) => {
  return Array.from({ length: count }, () => 
    Math.floor(Math.random() * (max - min + 1)) + min
  );
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  
  // 销毁已存在的图表实例
  if (chartInstance) {
    chartInstance.dispose();
  }
  
  // 创建新的图表实例
  chartInstance = echarts.init(chartRef.value);
  
  // 获取日期标签
  const dateLabels = generateDateLabels.value;
  
  // 生成随机数据
  const orderCount = generateRandomData(50, 200, dateLabels.length);
  
  // 配置图表选项
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params: any) {
        const dataIndex = params[0].dataIndex;
        const date = dateLabels[dataIndex];
        const value = params[0].value;
        return `${date}: ${value}单`;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dateLabels,
      axisLine: {
        lineStyle: {
          color: '#E0E0E0'
        }
      },
      axisLabel: {
        color: '#909399'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#EBEEF5'
        }
      },
      axisLabel: {
        color: '#909399'
      }
    },
    series: [
      {
        name: '订单数量',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#4066FF'
        },
        lineStyle: {
          width: 3,
          color: '#4066FF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(64, 102, 255, 0.3)'
            },
            {
              offset: 1,
              color: 'rgba(64, 102, 255, 0.1)'
            }
          ])
        },
        data: orderCount
      }
    ]
  };
  
  // 设置图表选项
  chartInstance.setOption(option);
  
  // 处理窗口大小变化
  window.addEventListener('resize', () => {
    chartInstance?.resize();
  });
};

// 监听时间范围变化，重新初始化图表
watch(() => props.timeRange, () => {
  initChart();
});

// 组件挂载时初始化图表
onMounted(() => {
  initChart();
});
</script>

<template>
  <div ref="chartRef" class="trend-chart"></div>
</template>

<style scoped>
.trend-chart {
  width: 100%;
  height: 100%;
}
</style> 